//备注：拷贝代码请加上作者信息
//作者：王海涛
//邮箱：1126471088@qq.com
//版本：V1.0.0
#include "tm1640_driver.h"
#include <stdint.h>

static volatile unsigned int* TM1640_SCL;
static volatile unsigned int* TM1640_SDA;


/* 简单延时函数 */
static void delay_us(void)
{
}
/* 启动信号 */
static void WHT_TM1640_Start(void)
{
    *TM1640_SCL = Hig;
    *TM1640_SDA = Hig;
    delay_us();
    *TM1640_SDA = Low;
    delay_us();
    *TM1640_SCL = Low;
    delay_us();
}
/* 结束信号 */
static void WHT_TM1640_Stop(void)
{
    *TM1640_SCL = Low;
    *TM1640_SDA = Low;
    delay_us();
    *TM1640_SCL = Hig;
    delay_us();
    *TM1640_SDA = Hig;
    delay_us();
}
/* 发送1字节 */
static void WHT_TM1640_Send_Byte(uint8_t value)
{
    for(uint8_t i = 0; i < 8; i++)
    {
        *TM1640_SCL = Low;
        delay_us();
        *TM1640_SDA = (value & 0x01) ? Hig : Low;
        value >>= 1;
        delay_us();
        *TM1640_SCL = Hig;
        delay_us();
    }
}



/* 显示初始化 */
static void WHT_TM1640_Init(void)
{
    WHT_GPIO_BSP.WHT_Set_Clock(TM1640_SCL_GPIO_PORT, ENABLE);
    WHT_GPIO_BSP.WHT_Set_Clock(TM1640_SDA_GPIO_PORT, ENABLE);
    WHT_GPIO_BSP.WHT_Set_Pin(TM1640_SCL_GPIO_PORT, TM1640_SCL_GPIO_PIN, Hig);
    WHT_GPIO_BSP.WHT_Set_Pin(TM1640_SDA_GPIO_PORT, TM1640_SDA_GPIO_PIN, Hig);
    WHT_GPIO_BSP.WHT_Set_Mode(TM1640_SCL_GPIO_PORT, TM1640_SCL_GPIO_PIN, Mode_Out_PP);
    WHT_GPIO_BSP.WHT_Set_Mode(TM1640_SDA_GPIO_PORT, TM1640_SDA_GPIO_PIN, Mode_Out_PP);
    WHT_GPIO_BSP.WHT_Register_Bit_Output(TM1640_SCL_GPIO_PORT, TM1640_SCL_GPIO_PIN, &TM1640_SCL);
    WHT_GPIO_BSP.WHT_Register_Bit_Output(TM1640_SDA_GPIO_PORT, TM1640_SDA_GPIO_PIN, &TM1640_SDA);
    
    WHT_Delay_ms(1);

    WHT_TM1640_Start();
    WHT_TM1640_Send_Byte(TM1640_DATA_CMD_Mode(Work_Auto_Mode)); // 数据命令设置：地址自动加1模式
    WHT_TM1640_Stop();

    WHT_TM1640_Driver.WHT_Set_Brightness(0); //关显示
}
/* 亮度设置 */
static void WHT_TM1640_Set_Brightness(uint8_t level)
{
    WHT_TM1640_Start();
    WHT_TM1640_Send_Byte(TM1640_DISPLAY_CMD(level > 8 ? 8 : level));
    WHT_TM1640_Stop();
}
/* 显示控制 */
static void WHT_TM1640_Display_Buffer(uint8_t start_addr, const uint8_t* buffer, uint8_t length)
{
    WHT_TM1640_Start();
    WHT_TM1640_Send_Byte(TM1640_ADDR_CMD(start_addr)); // 地址命令：起始地址
    for(uint8_t i = 0; i < length; i++)
    {
        WHT_TM1640_Send_Byte(buffer[i]);
    }
    WHT_TM1640_Stop();
}



const WHT_TM1640_Driver_t WHT_TM1640_Driver =
{
    .WHT_Init              = WHT_TM1640_Init,
    .WHT_Set_Brightness    = WHT_TM1640_Set_Brightness,
    .WHT_Display_Buffer    = WHT_TM1640_Display_Buffer,
};
